﻿using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using System;

namespace DX.DbStorage.EF
{
    public static class Converters
    {
        public static ValueConverter Timestamp()
        {
            return new ValueConverter<DateTime, long>(to => new DateTimeOffset(to).ToUnixTimeMilliseconds(),
            from => DateTimeOffset.FromUnixTimeMilliseconds(from).LocalDateTime);
        }
     
   
        public static ValueConverter NullTimestamp()
        {
            return new ValueConverter<DateTime?, long?>(x => To(x), x => From(x));
        }
        public static ValueConverter Enum<TEnum>() where TEnum : struct
        {
            return new ValueConverter<TEnum, string>(x => x.ToString(), x => From<TEnum>(x));
        }
        public static ValueConverter EnumUpper<TEnum>() where TEnum : struct
        {
            return new ValueConverter<TEnum, string>(x => x.ToString().ToUpper(), x => From<TEnum>(x));
        }
        public static ValueConverter EnumLower<TEnum>() where TEnum : struct
        {
            return new ValueConverter<TEnum, string>(x => x.ToString().ToLower(), x => From<TEnum>(x));
        }
        static DateTime? From(long? value)
        {
            if (value == null) return null;
            return DateTimeOffset.FromUnixTimeMilliseconds(value.Value).LocalDateTime;
        }
        static long? To(DateTime? value)
        {
            if (value == null) return null;
            return new DateTimeOffset(value.Value).ToUnixTimeMilliseconds();
        }

        static TEnum From<TEnum>(string value) where TEnum : struct
        {
            if (System.Enum.TryParse<TEnum>(value, true, out TEnum result)) return result;
            return default(TEnum);
        }
    }


}
